<template>
  <Page class="bg-[#f8f9fa] text-[#333] min-h-screen">
    <!-- 头部区域 -->
    <view class="max-w-[750rpx] mx-auto sticky top-0 z-[2]">
      <!-- 头部区域 -->
      <PageHeader title="日结区" :showBack="true" :onlyBack="true" />
      <view class="bg-gradient-to-r from-[#165DFF] to-[#1890ff] sticky top-0 z-[2] text-white px-[32rpx] pt-[100rpx] pb-[20rpx] rounded-b-[32rpx] mb-[-40rpx] relative shadow-md">
        <!-- 返回按钮 -->
        <SearchView @search="handleSearch" @clear="handleClear" />
      </view>
    </view>

    <!-- 分类区域 -->
    <view class="flex overflow-x-auto p-[16rpx_32rpx] mt-[40rpx] bg-white gap-x-[16rpx]">
      <view
        v-for="category in categories"
        :key="category.id"
        class="flex flex-col items-center min-w-[88rpx] p-[16rpx_12rpx] rounded-[20rpx] cursor-pointer transition-all duration-300 border-2"
        :class="{
          'bg-gradient-to-r from-[#2196F3] to-[#1890ff] text-white border-[#2196F3] shadow-md': activeTab === category.id,
          'bg-white text-[#666] border-[#e0e0e0] hover:border-[#2196F3] hover:text-[#2196F3]': activeTab !== category.id,
        }"
        @click="
          activeTab = category.id;
          handleCategoryClick(category.name);
        "
      >
        <view
          class="category-name text-[24rpx] text-center font-medium leading-[1.2] whitespace-nowrap"
          :class="{
            'text-white font-bold': activeTab === category.id,
            'text-[#666]': activeTab !== category.id,
          }"
        >
          {{ category.name }}
        </view>
      </view>
    </view>

    <!-- 适合人群选择 -->
    <view class="px-6 mt-3 flex items-center">
      <view class="text-[24rpx] text-gray-600 mr-2">适合人群:</view>
      <view class="flex flex-wrap gap-2 flex-1 overflow-x-auto flex-nowrap">
        <!-- 人群选项 -->
        <view 
          v-for="item in suitablePersons" 
          :key="item.id"
          class="px-3 py-1 rounded-full border transition-all duration-200 cursor-pointer"
          :class="selectedGroupId === item.id ? 'bg-blue-600 border-blue-600 text-white' : 'bg-gray-100 border-gray-300 text-gray-600'"
          @click="selectGroup(item.id)"
        >
          <text class="text-[22rpx] whitespace-nowrap">{{ item.name }}</text>
        </view>
      </view>
    </view>

    <view class="order-list p-[24rpx_32rpx] min-h-[calc(100vh-420rpx)] flex flex-col gap-y-[20rpx]">
      <view
        v-for="(order, index) in filteredOrders"
        :key="index"
        @tap="goDetail(order.id!)"
        class="order-card bg-white rounded-[24rpx] p-[24rpx] shadow-md relative flex flex-col"
        :class="order.status ? 'border-l-[8rpx] border-l-[#FF4D4F]' : 'border-l-[8rpx] border-l-[#165DFF]'"
      >
        <view>
          <view class="order-header flex justify-between mb-[16rpx] items-start">
            <view class="order-title text-[28rpx] font-bold flex-1 text-[#222]">{{ order.position_name }} </view>
            <view class="text-[22rpx] px-[20rpx] py-[8rpx] rounded-[16rpx] font-medium bg-gradient-to-r from-[#e3f2fd] to-[#bbdefb] text-[#2196F3]">
              {{ change(order) }}
            </view>
          </view>

          <view class="order-meta flex mb-[12rpx] flex-wrap gap-x-[16rpx] gap-y-[8rpx]">
            <view class="meta-item flex items-center text-[22rpx] text-[#666]">
              <IconFont name="locationg3" class="mr-[8rpx] text-[#165DFF]" size="12" />
              <text>{{ order.location }}</text>
            </view>
            <view class="meta-item flex items-center text-[22rpx] text-[#666]">
              <IconFont font-class-name="iconfont" class-prefix="icon" name="building" class="text-blue-500 text-[40rpx] mr-1" size="12" />
              <text>{{ order.corporate_name }}</text>
            </view>
          </view>
          <view class="order-footer flex flex-col mt-[16rpx]">
            <view class="grid grid-cols-1 gap-[16rpx] mb-[18rpx] text-[24rpx]">
              <view class="flex gap-2">
                <span class="text-[#999]">录用人数</span>
                <span class="text-[#52c41a] font-bold">{{ order.number }}人</span>
              </view>
              <view class="text-[24rpx] text-[#666] line-clamp-3">职位描述：{{ order.description }}</view>
            </view>

            <view class="flex flex-wrap gap-[16rpx] mb-[18rpx] text-[24rpx] text-[#666] justify-between">
              <view>要求：{{ order.experience }}</view>
              <view>
                日薪：<text class="text-[#ff0000]">¥{{ order.salary }}</text>
              </view>
            </view>

            <!-- 元信息 -->
            <view class="flex justify-between text-[22rpx] text-[#999] mb-[18rpx]">
              <!-- <view>开始时间：{{ order.start_date }}</view> -->
              <view>截止时间：{{ order.end_date || order.deadline }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载更多按钮 -->
    <view class="flex justify-center mt-[20rpx] mb-[30rpx]">
      <nut-button
        size="normal"
        type="primary"
        :loading="isLoading"
        :disabled="isLoading || !hasMore"
        @click="loadMore"
        class="w-[300rpx] bg-[#2196F3] border-[#2196F3] rounded-[24rpx] py-[16rpx] text-[28rpx] font-medium shadow-sm transition-all duration-300"
      >
        {{ !hasMore ? "没有更多了" : "加载更多" }}
      </nut-button>
    </view>
  </Page>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
// import { Input as nutInput, Button as nutButton } from "@nutui/nutui-taro";
import PageHeader from "@/components/PageHeader.vue";
import SearchView from "@/components/SearchView.vue";
// import IconFont from "@/components/IconFont.vue";
import { post } from "@/utils/request";
// 返回上一页
const goBack = () => {
  Taro.navigateBack({
    delta: 1,
  });
};

// 搜索文本
const searchText = ref("");

// 适合人群列表
const suitablePersons = ref<any[]>([]);
// 选中的适合人群ID
const selectedGroupId = ref<number>(0); // 默认为"不限"

//定义标签数据获取格式
interface tagsColumn {
  update_time: number;
  create_time: number;
  name: string;
  id: number;
}

interface tagsItem {
  columns: tagsColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

interface QueryParams {
  pageNo?: number;
  pageSize?: number;
  type?: number;
  status?: number;
}

interface OrderColumn {
  member_id: null;
  create_time: null;
  time_frame: null;
  pay_number: null;
  position_name: null;
  description: null;
  type: null;
  experience: null;
  salary: null;
  number: null;
  pay_status: null;
  update_time: null;
  name: null;
  corporate_name: null;
  location: null;
  id: null;
  deadline: null;
  end_date: null;
  status: null;
}

interface OrderItem {
  columns: OrderColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

// 分类数据
const categories = ref([
  {
    name: "全部",
    id: 0,
  },
  /*{name: "餐饮", icon: "icon-restaurant"},
  {name: "促销", icon: "icon-promotion"},
  {name: "搬运", icon: "icon-move"},
  {name: "配送", icon: "icon-delivery"},
  {name: "家政", icon: "icon-housekeeping"},
  {name: "家教", icon: "icon-teacher"},
  {name: "礼仪", icon: "icon-etiquette"},
  {name: "维修", icon: "icon-repair"},*/
]);
const activeCategory = ref(0);

// 优先级筛选
const priorityFilters = ["全部订单", "急招订单"];
const activeFilter = ref(0);
const allOrders = ref([
  {
    member_id: null,
    create_time: null,
    time_frame: null,
    pay_number: null,
    position_name: null,
    description: null,
    type: null,
    experience: null,
    salary: null,
    number: null,
    pay_status: null,
    update_time: null,
    name: null,
    corporate_name: null,
    location: null,
    id: null,
    deadline: null,
    end_date: null,
    status: null,
  },
]);
// 订单数据
const orders = ref([
  {
    member_id: null,
    create_time: null,
    time_frame: null,
    pay_number: null,
    position_name: null,
    description: null,
    type: null,
    experience: null,
    salary: null,
    number: null,
    pay_status: null,
    update_time: null,
    name: null,
    corporate_name: null,
    location: null,
    id: null,
    deadline: null,
    end_date: null,
    status: null,
  },
]);

// 活跃状态
const activeRole = ref("user"); // user, worker, merchant
const activeTab = ref(0);
const tagsType = ref([]);

let hasMore = true; // 是否还有更多
let pageNo = 1;
let pageSize = 10;
const isLoading = ref(false); // 加载中状态
const handleClear = () => {
  searchText.value = "";
  resetPagination();
  getTaskAll(0);
};

// 处理搜索
const handleSearch = (txt: string) => {
  searchText.value = txt;
  resetPagination();
  getTaskAll(0);
};

// 选择适合人群
const selectGroup = (groupId: number) => {
  selectedGroupId.value = groupId;
  resetPagination(); // 重置分页
  getTaskAll(activeTab.value); // 重新请求数据
  
  // 显示选择提示
  const groupName = groupId === 0 ? '不限' : suitablePersons.value.find(item => item.id === groupId)?.name || '未知';
  Taro.showToast({
    title: `已选择：${groupName}`,
    icon: 'none',
    duration: 1500
  });
};

// 重置分页参数
const resetPagination = () => {
  pageNo = 1;
  allOrders.value = [];
  hasMore = true;
};

// 加载更多
const loadMore = () => {
  if (isLoading.value || !hasMore) return;
  getTaskAll(activeTab.value);
};

//获取日结招聘标签
getTags();
function getTags() {
  post("/dictionary/recruitmentDailyLabel").then((res) => {
    const newItems = res.data.map((item: tagsItem) => ({
      update_time: item.columns.update_time,
      create_time: item.columns.create_time,
      name: item.columns.name,
      id: item.columns.id,
    }));
    categories.value.push(...newItems);
  });
}

// 获取适合人群列表
const getSuitablePersons = async () => {
  try {
    const res = await post("/dictionary/groupTypes");
    console.log("res==>人群",res.data)
    if (res.code === 0 && res.data) {
      // 根据接口返回的数据结构处理人群列表
      suitablePersons.value = res.data.map((item: any) => item.columns);
      suitablePersons.value.unshift({ id: 0, name: "不限" });
    }
  } catch (error) {
    console.error("获取适合人群列表失败:", error);
    // 设置默认人群列表作为备用
    suitablePersons.value = [
      { id: 1, name: "学生" },
      { id: 2, name: "上班族" },
      { id: 3, name: "自由职业者" },
      { id: 4, name: "退休人员" }
    ];
  }
};

// 处理详情点击
const goDetail = (id: number | string) => {
  Taro.navigateTo({
    url: `/pages-detail/post/recruit/order-acceptance-detail?id=${id}`,
  });
};

// 处理分类点击
const handleCategoryClick = (categoryName: string) => {
  resetPagination(); // 重置分页
  getTaskAll(activeTab.value); // 重新请求数据

  // Taro.showToast({
  //   title: `已筛选: ${categoryName}类订单`,
  //   icon: "none",
  //   duration: 2000,
  // });
};

// 处理筛选点击
const handleFilterClick = computed(() => {
  return categories.value.filter((item) => item.id === activeCategory.value);
});

// 处理接单
const handleTakeOrder = (taskTitle: string) => {
  const submitForm = {
    recruitmentId: orders.value.find((item) => item.position_name === taskTitle)?.id,
    type: 2,
  };
  //console.log("报名的ID",submitForm.recruitmentId)
  post("/recruitmentDaily/signUp", submitForm).then((res) => {
    Taro.showToast({
      title: `您已申请接单: ${taskTitle}\n等待雇主确认中...`,
      icon: "none",
      duration: 2000,
    });
    if (res.code === 0) {
      Taro.showToast({
        title: `报名成功`,
        icon: "none",
        duration: 2000,
      });
    } else {
      Taro.showToast({
        title: `报名失败`,
        icon: "none",
        duration: 2000,
      });
    }

    getTaskAll(0);
  });
};
const newItems = ref([] as typeof allOrders.value);
const getTaskAll = async (type: number) => {
  // 防止重复请求
  if (isLoading.value || !hasMore) {
    if (!hasMore) {
      Taro.showToast({ title: "没有更多了", icon: "none" });
    }
    return;
  }

  isLoading.value = true; // 开始加载

  try {
    const queryParams: any = {
      pageNo: pageNo,
      pageSize: pageSize,
      type: type,
      status: 0,
    };

    if (searchText.value) {
      queryParams.title = searchText.value;
    }

    queryParams.groupTypes = selectedGroupId.value || 0;

    const res = await post("/recruitmentDaily/all", queryParams);

    if (res.code === 0) {
      const newItems = res.data.map((item: OrderItem) => ({
        ...item.columns,
        member_id: item.columns.member_id,
        create_time: item.columns.create_time,
        time_frame: item.columns.time_frame,
        pay_number: item.columns.pay_number,
        position_name: item.columns.position_name,
        description: item.columns.description,
        type: item.columns.type,
        experience: item.columns.experience,
        salary: item.columns.salary,
        number: item.columns.number,
        pay_status: item.columns.pay_status,
        update_time: item.columns.update_time,
        name: item.columns.name,
        corporate_name: item.columns.corporate_name,
        location: item.columns.location,
        id: item.columns.id,
        end_date: item.columns.end_date,
        status: item.columns.status,
      }));

      // 第一页直接赋值，后续页追加数据
      if (pageNo === 1) {
        allOrders.value = newItems;
      } else {
        allOrders.value = [...allOrders.value, ...newItems];
      }

      // 判断是否还有更多数据
      if (newItems.length < pageSize) {
        hasMore = false;
      } else {
        pageNo++; // 页码+1，下次加载下一页
      }
    } else {
      Taro.showToast({ title: res.msg || "加载失败", icon: "none" });
    }
  } catch (error) {
    console.error("获取任务数据失败：", error);
    Taro.showToast({ title: "加载失败", icon: "none" });
  } finally {
    isLoading.value = false; // 结束加载
  }
};
// 定义computed属性，根据筛选条件动态过滤
const filteredOrders = computed<OrderColumn[]>(() => {
  //活跃标签为0时显示全部数据
  if (activeTab.value === 0) {
    return allOrders.value;
  }
  return allOrders.value.filter((order) => order.type === activeTab.value);
});
//orders.value = filteredOrders.value
//orders.value = allOrders.value
//orders.push(allOrders.value)
//分页
/*let list = allOrders.value
  if (activeTab.value > 0) {
    orders = orders.filter(c => c.category === categories[activeTab.value])
  }
  filteredCourses.value = list.slice(0, page.value * pageSize)
  noMore.value = filteredCourses.value.length >= list.length*/

// 消息按钮点击
const handleMessageClick = () => {
  Taro.showToast({
    title: "查看最新任务通知",
    icon: "none",
    duration: 2000,
  });
};

//状态转换方法
const change = (item: any) => {
  console.log("item为", item);
  // item.releaseStatus 发布状态，招聘、日结类：1 待支付 2 审核中 3 审核通过 4 审核不过 5 停止招聘
  if (item.releaseStatus) {
    switch (item.releaseStatus) {
      case 1:
        return "待支付";
      case 2:
        return "审核中";
      case 3:
        return "招聘中";
      case 4:
        return "停止招聘";
      case 5:
        return "停止招聘";
      default:
        break;
    }
  }
  return "招聘中";
  // switch (item) {
  //   case 1:
  //     return "招聘中";
  //   case 2:
  //     return "停止招聘";
  //   case 0:
  //     return "未知状态";
  // }
  // return "招聘中";
};
onMounted(() => {
  getTaskAll(0);
  getSuitablePersons(); // 获取适合人群列表
});
</script>
